package edu.friday.controller;

import edu.friday.common.exception.BaseException;
import edu.friday.common.result.RestResult;
import edu.friday.utils.IdUtils;
import edu.friday.utils.RedisCache;
import edu.friday.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @description:
 **/
@RestController
public class CommonController {

  @Autowired
  private RedisCache redisCache;

  @ResponseBody
  @GetMapping("t")
  public RestResult test() {
    return RestResult.success();
  }

  @GetMapping("api")
  public void apiDocs(HttpServletResponse response) throws IOException {
    response.sendRedirect("swagger-ui.html");
  }

  @GetMapping("druid")
  public void druid(HttpServletResponse response) throws IOException {
    response.sendRedirect("/druid/index.html");
  }

  @GetMapping(value = "profile/avatar/{userName}/{fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
  public byte[] staticFile(@PathVariable String userName, @PathVariable String fileName) throws IOException {
    File file = new File(FileUploadUtils.getAvatarAbsolutePath(userName, fileName));
    if (!file.exists()) {
      throw new BaseException("获取文件失败");
    }
    FileInputStream inputStream = new FileInputStream(file);
    byte[] bytes = new byte[inputStream.available()];
    inputStream.read(bytes, 0, inputStream.available());
    return bytes;
  }

  /**
   * 生成验证码
   */
  @GetMapping("/captchaImage")
  public RestResult getCode(HttpServletResponse response) throws IOException {
    // 生成随机字串
//        String verifyCode = "123";
//        verifyCode = VerifyCodeUtils.generateVerifyCode(4);
    // 唯一标识
    String uuid = IdUtils.simpleUUID();
//        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
    RestResult ajax = RestResult.success();
    ajax.put("uuid", uuid);
    return ajax;
  }

}
